Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

191
Visualizações
How to call MongoDB CRUD operations from outside of the async run function | JS

The following code is the default async run function for the MongoDB JS driver.

async function run() {
  try {
    await client.connect();
    const database = client.db('sample_mflix');
    const movies = database.collection('movies');
    // Query for a movie that has the title 'Back to the Future'
    const query = { title: 'Back to the Future' };
    const movie = await movies.findOne(query);
    console.log(movie);
  } finally {
    // Ensures that the client will close when you finish/error
    await client.close();
  }
}
run().catch(console.dir);

Is there any way on earth to do the CRUD operations etc outside of that function, e.g in an expressjs endpoint?

Thanks.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You can have a function that connects to the DB, probably in a different file and export the function

// DB.js
async function connectToDatabase() {
  try {
    await client.connect();
    return client.db('sample_mflix');
  } catch(err) {
    console.dir(err);
  } finally {
    await client.close();
  }
}

Then import it if you're using the export method, or just call the function

app.get('/api/path', () => {
  const db = await connectToDatabse();

  if (db) {
    const query = {
      title: 'Back to the Future'
    };

    const movie = await db.collection('movies').findOne(query);
    console.log(movie)
  }
})
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda